<?php
namespace app\controllers;
use Yii;
use app\models\MessageSearch;
use app\models\Message;
use yii\web\ConflictHttpException;
use app\models\MessageText;
use app\models\User;
use app\models\Email;
use app\models\EmailSearch;
use app\components\PHPMailer;

class MessageController extends \app\components\Controller
{
    public $layout='@app/views/layouts/column_two.php';
    public $userModel;
    /**
     * get the user information
     * @author : nonglei
     * @date   : 22/04/2014
     */
	public function UserInfo()
	{
		$username = null;
		$this->userModel = User::find()->where(array("user_name"=>yii::$app->user->identity->user_name))->one();
	}
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
    {
        $model = $this->loadModel($id);
        $this->UserInfo();
        $userID = $this->userModel->user_id;
        $nextModel = null;
        if($model->receiver_id == $userID)
        {
            $nextModel = Message::find()->where("create_date > \"{$model->create_date}\" and receiver_id = {$userID} and status != 1")->all();
        }
        else
        {
            $nextModel = Message::find()->where("create_date > \"{$model->create_date}\" and sender_id = {$userID} and status != 0")->all();
        }
        if($model->receiver_id == $this->userModel->user_id && $model->isRead == Message::FLAG_UNREAD)
        {
            $model->isRead = Message::FLAG_READ;
            if($model->save())
            {
            }
        }
        $newModel = new Message;
		if(isset($_POST['Message']))
        {
            $date = date('Y-m-d H:i:s',time());
            $form = $_POST['Message'];
            $newModel->sender_id = yii::$app->user->identity->user_id;
            $newModel->receiver_id = $model->sender_id;
            $newModel->create_date = $date;
            $newModel->verifyCode = $form['verifyCode'];
            $keyword = substr($model->title,0,6);
            if($keyword == "Reply:")
            {
                $keyword = substr($model->title,0,count($model->title)-23);
                $newModel->title = $keyword." on ".$date;
            }
            else
            {
                $newModel->title = "Reply:".$model->title." on ".$date;
            }
            $messageText = new MessageText;
            $messageText->content = $form['content'];
            if($messageText->save())
            {
                $newModel->messageText_id = $messageText->messageText_id;
            }
            $newModel->content = $form['content'];
            if($newModel->save())
            {
                return $this->redirect(array('message/sent'));
            }
		}

        return $this->render('view',array(
            'model'=>$model,
            'newModel'=>$newModel,
            'nextModel'=>$nextModel[0],
        ));
    }
    /**
     * contact to admin
     * @author : nonglei
     * @date   : 23/04/2014
     */
    public function actionComposeToAdmin()
    {
        $model=new Message;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Message']))
        {
            $form = $_POST['Message'];
            $model->sender_id = yii::app()->user->id;
            $user = $this->loadUserModel(yii::app()->params['adminUserName']);
            $model->receiver_id = $user->user_id;
            if($model->sender_id == $model->receiver_id)
            {
                throw new ConflictHttpException("Sorry !  You can not send a message to yourself.");
            }
            $messageText = new MessageText;
            $messageText->content = $form['content'];
            if($messageText->save())
            {
                $model->messageText_id = $messageText->messageText_id;
            }
            $model->content = $form['content'];
            $model->title = $form['title'];
            $model->verifyCode = $form['verifyCode'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->message_id));
		}
		$this->render('composetoadmin',array(
			'model'=>$model,
		));
    }
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Message;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
        $this->UserInfo();
        $userModel = $this->userModel;

        if(isset($_POST['Message']))
        {
            $form = $_POST['Message'];
            $model->sender_id = $userModel->user_id;
            $user = $this->loadUserModel($form['receiver_id']);
            $model->receiver_id = $user->user_id;
            $model->verifyCode = $form['verifyCode'];
            if($model->sender_id == $model->receiver_id)
            {
                throw new ConflictHttpException('Can not sent message to yourself.');
            }
            $messageText = new MessageText;
            $messageText->content = $form['content'];
            if($messageText->save())
            {
                $model->messageText_id = $messageText->messageText_id;
            }
            $model->content = $form['content'];
            $model->title = $form['title'];
			if($model->save())
				return $this->redirect(array('view','id'=>$model->message_id));
		}
		return $this->render('create',array(
            'model'=>$model,
            'userModel'=>$userModel,
		));
	}

    public function actionGroupcompose()
    {
       $newModel=new Message;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Message']))
        {
            $form = $_POST['Message'];
            $userList = User::getUserNameListForMessage($form['grade'], $form['department'], $form['professional'], $form['class']);
            if($userList === NULL)
            {
                throw new ConflictHttpException("Sorry! No users be found.");
            }
            $messageText = new MessageText;
            $messageText->content = $form['content'];
            if(!$messageText->save())
            {
                throw new ConflictHttpException("Sorry! Some Error IN Save MessageText.");
            }
            foreach($userList as $elem)
            {
		        $model = new Message;
                $user = $this->loadUserModel($elem);
                $model->sender_id = yii::$app->user->identity->user_id;
                $model->receiver_id = $user->user_id;
                $model->verifyCode = $form['verifyCode'];
                $model->messageText_id = $messageText->messageText_id;
                $model->title = $form['title'];
                if(!$model->save())
                {
                    throw new ConflictHttpException("Sorry! Can't sent this message.");
                }
                $newModel->message_id = $model->message_id;
            }
            $this->redirect(array('view','id'=>$model->message_id));
		}

		return $this->render('groupcompose',array(
			'model'=>$newModel,
		));
    }


	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
        $model = $this->loadModel($id);
        if($model->status == Message::STATUS_IN_ALL)
        {
            if($model->receiver_id == yii::$app->user->identity->user_id)
            { 
                $model->status -= 1;
                $model->save();
            }
            else
            {
                $model->status -= 2;
                $model->save();
            }
        }
        else
        {
            $messageText = $model->messageText;
            if(count(Message::find()->where(array('messageText_id'=>$messageText->messageText_id))) == 1)
            {
                $model->delete();
                $messageText->delete();
            }
            else
            {
                $model->delete();
            }
        }
        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if(!isset($_GET['ajax']))
            return $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('inbox'));
    }
    /**
     * show sent
     * @author : nonglei
     * @date   : 22/04/2014
     */
    public function actionSent()
    {
         if(isset($_POST['submitDelete']))
         {
            $array = $_POST['selection'];
            if($array !== NULL)
            foreach($array as $elem)
            {
                $model = $this->loadModel($elem);
                if($model->status == Message::STATUS_IN_ALL)
                {
                    $model->status -= 2;
                    $model->save();
                }
                else
                {
                    $messageText = $model->messageText;
                    if(count(Message::find()->where(array('messageText_id'=>$messageText->messageText_id))) == 1)
                    {
                        $model->delete();
                        $messageText->delete();
                    }
                    else
                    {
                        $model->delete();
                    }
                }
            }
        }
        $searchModel = new MessageSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams,'sent');
        return $this->render('sent', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);

	}
	/**
     * show inbox
     * @author : nonglei
     * @date   : 22/04/2014
     */
    public function actionInbox()
    {
        if(isset($_POST['submitDelete']))
        {
            $array = $_POST['selection'];
            if($array !== NULL)
            foreach($array as $id)
            {
                $model = $this->loadModel($id);
                if($model->status == Message::STATUS_IN_ALL)
                {
                    $status = $model->status - 1;
                    $model->status = $status;
                    $model->save();
                }
                else
                {
                    $messageText = $model->messageText;
                    if(count(Message::find()->where(['messageText_id'=>$messageText->messageText_id])) == 1)
                    {
                        $model->delete();
                        $messageText->delete();
                    }
                    else
                    {
                        $model->delete();
                    }
                }
            }
        }
        if(isset($_POST['submitUnread']))
        {
            $array = $_POST['selection'];
            if($array !== NULL)
            foreach($array as $id)
            {
                $elem = Message::find()->where(['message_id' => $id])->one();
                $elem->isRead = Message::FLAG_UNREAD;
                $elem->save();
            }
        }
        if(isset($_POST['submitRead']))
        {
            $array = $_POST['selection'];
            if($array !== NULL)
            foreach($array as $id)
            {
                $elem = Message::find()->where(['message_id' => $id])->one();
                $elem->isRead = Message::FLAG_READ;
                $elem->save();
            }
        }

        $searchModel = new MessageSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams,'inbox');
        return $this->render('inbox', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
 	}
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Message');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Message('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Message']))
			$model->attributes=$_GET['Message'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

    public function actionViewemail($id)
    {
        return $this->render('viewemail',array(
            'model'=>Email::find()->where(['id'=>$id])->one(),
        ));
    }
    public function actionEmailone()
	{
		$model=new Email;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
        $this->UserInfo();
        $userModel = $this->userModel;
        if(isset($_POST['Email']))
        {
            $model->user_id = $userModel->user_id;
            $model->title = $_POST['Email']['title'];
            $model->content = $_POST['Email']['content'];
            $model->receiver = $_POST['Email']['receiver'];
            $user = $this->loadUserModel($_POST['Email']['receiver']);
            $userEmail = $user->email;
            if($model->save())
            {
                $body = $model->content;
                $subject = $model->title;
                $address = $userEmail;
                $name = $user->nick_name;
                $fromname = $userModel->email;
                $this->sendEmail($body,$subject,$address,$name,$fromname);
				return $this->redirect(array('message/viewemail','id'=>$model->id));
            }
		}
		return $this->render('emailone',array(
            'model'=>$model,
            'userModel'=>$userModel,
		));
	}

    public function actionEmailgroup()
    {
        $model = new Email;
        if(isset($_POST['Email']))
        {
            $this->UserInfo();
            $userModel = $this->userModel;
            $form = $_POST['Email'];
            $userList = User::getUserNameListForMessage($form['grade'], $form['department'], $form['professional'], $form['class']);
            if($userList === NULL)
            {
                throw new ConflictHttpException("Sorry! No users be found.");
            }
            $model->user_id = $userModel->user_id;
            $model->title = $_POST['Email']['title'];
            $model->content = $_POST['Email']['content'];
            $model->receiver = implode(',',$userList);
            if($model->save())
            {
                foreach($userList as $elem)
                {
                    $user = $this->loadUserModel($elem);
                    $userEmail = $user->email;
                    $body = $model->content;
                    $subject = $model->title;
                    $address = $userEmail;
                    $name = $user->nick_name;
                    $fromname = $userModel->email;
                    $this->sendEmail($body,$subject,$address,$name,$fromname);
                }
            }
            return $this->redirect(array('message/viewemail','id'=>$model->id));
		}

		return $this->render('emailgroup',array(
            'model'=>$model,
            'userModel'=>$userModel,
		));
	}


    public function actionEmailsent()
    {
        $searchModel = new EmailSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('emailsent', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionDeleteemail($id)
    {
        $email = Email::find()->where(['id'=>$id])->one();
        $email->delete();
        if(!isset($_GET['ajax']))
            return $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('message/emailsent'));
    }



	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Message the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model = Message::find()->where(['message_id' => $id])->one();
		if($model===null)
			throw new ConflictHttpException("Error, The user \"$id\" is not exist.");
		return $model;
	}
	public function loadUserModel($id)
	{
		$model=User::find()->where(['user_name' => $id, 'status'=>1])->one();
		if($model===null)
			throw new ConflictHttpException("Error, The user \"$id\" is not exist.");
		return $model;
	}
	/**
	 * Performs the AJAX validation.
	 * @param Message $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='message-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
    public function sendEmail($body,$subject,$address,$name,$fromname)
    {
            $mail = new PHPMailer(); //建立邮件发送类
            $mail->CharSet ="UTF-8";
            $mail->IsSMTP(); // 使用SMTP方式发送
            $mail->Host = "smtp.exmail.qq.com"; // 您的企业邮局域名
            $mail->Post = 25; // 您的企业邮局域名
            $mail->SMTPAuth = true; // 启用SMTP验证功能
            $mail->Username = "guetoj@rayor.cn"; // 邮局用户名(请填写完整的email地址)
            $mail->Password = "goj2014"; // 邮局密码

            $mail->From = "guetoj@rayor.cn"; //邮件发送者email地址
            $mail->FromName = $fromname;
            $mail->AddAddress("$address", "$name");//收件人地址，可以替换成任何想要接收邮件的email信箱,格式是AddAddress("收件人email","收件人姓名")

            ////$mail->AddAttachment("/var/tmp/file.tar.gz"); // 添加附件
            $mail->IsHTML(true); // set email format to HTML //是否使用HTML格式
            $mail->Subject = "$subject"; //邮件标题
            $mail->Body = "$body"; //邮件内容
            //$mail->AltBody = "This is the body in plain text for non-HTML mail clients"; //附加信息，可以省略
            if(!$mail->send())
            {
                $this->errorMessage = $mail->ErrorInfo;
                return false;
            }
            else
            {
                return true;
            }
    }



}
